//
//  CustomTabBarItem.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/15.
//

import UIKit

class LYCustomTabBarItem: UIControl {
    
    var title: String? {
        didSet {
            titleLabel.text = title
        }
    }
    
    var icon: UIImage? {
        didSet {
            iconImageView.image = icon
        }
    }
    
    var selectedIcon: UIImage?
    
    var normalColor: UIColor = .gray {
        didSet {
            updateAppearance()
        }
    }
    
    var selectedColor: UIColor = .systemBlue {
        didSet {
            updateAppearance()
        }
    }
    
    override var isSelected: Bool {
        didSet {
            updateAppearance()
        }
    }
    
    private let iconImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFit
        return imageView
    }()
    
    private let titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 10)
        label.textAlignment = .center
        return label
    }()
    
    private let stackView: UIStackView = {
        let stack = UIStackView()
        stack.axis = .vertical
        stack.alignment = .center
        stack.distribution = .fill
        stack.spacing = 4
        stack.isUserInteractionEnabled = false
        return stack
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }
    
    private func setupView() {
        addSubview(stackView)
        
        stackView.addArrangedSubview(iconImageView)
//        stackView.addArrangedSubview(titleLabel)
        
        stackView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            stackView.centerXAnchor.constraint(equalTo: centerXAnchor),
            stackView.centerYAnchor.constraint(equalTo: centerYAnchor),
            
            iconImageView.heightAnchor.constraint(equalToConstant: 24),
            iconImageView.widthAnchor.constraint(equalToConstant: 24)
        ])
    }
    
    private func updateAppearance() {
        if isSelected {
            titleLabel.textColor = selectedColor
            iconImageView.image = selectedIcon ?? icon
            iconImageView.tintColor = selectedColor
        } else {
            titleLabel.textColor = normalColor
            iconImageView.image = icon
            iconImageView.tintColor = normalColor
        }
    }
}
